<template>
  <el-card>
    <div class="fixed_header">
      <el-row type="flex" justify="space-between" style="margin-bottom: 10px">
        <el-col>
          <el-button size="small" @click="handleBack">返回上一页</el-button>
          <span style="font-weight: bold; margin-left: 10px">{{ title }}</span>
        </el-col>
        <div>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>
      </el-row>
    </div>
    <el-form
      class="form-container"
      :model="formModel"
      label-width="150px"
      :rules="rules"
      ref="form"
    >
      <el-card style="margin-bottom: 10px">
        <el-form-item label="用户类型">
          <el-radio-group
            v-model="formModel.userType"
            :disabled="!!userId"
            @change="handleCardChange"
          >
            <el-radio-button v-for="item in userTypeList" :label="item.value">{{
              item.label
            }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-card>
      <!-- 员工 -->
      <template v-if="formModel.userType === 1">
        <el-card style="margin-bottom: 10px">
          <el-col :span="8">
            <el-form-item label="姓名" prop="nickName">
              <el-input
                v-model="formModel.nickName"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="机构" prop="orgId">
              <el-select
                v-model="formModel.orgId"
                placeholder="请选择"
                style="width: 100%"
                @change="handleOrg"
              >
                <el-option
                  v-for="item in orgList"
                  :key="item.deptId"
                  :value="item.deptId"
                  :label="item.deptName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="部门" prop="deptId">
              <el-select
                v-model="formModel.deptId"
                style="width: 100%"
                :disabled="!formModel.orgId"
              >
                <el-option
                  v-for="item in deptList"
                  :value="item.deptId"
                  :label="item.deptName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="phonenumber">
              <el-input
                v-model="formModel.phonenumber"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号" prop="idNumber">
              <el-input
                placeholder="请输入"
                v-model="formModel.idNumber"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="职位">
              <el-input
                placeholder="请输入"
                v-model="formModel.postName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="住址">
              <el-input
                placeholder="请输入"
                v-model="formModel.address"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生日">
              <el-date-picker
                type="date"
                v-model="formModel.birthday"
                placeholder="请选择"
                style="width: 100%"
                :format="'yyyy-MM-dd'"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别">
              <el-radio-group v-model="formModel.sex">
                <el-radio label="1">男</el-radio>
                <el-radio label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-card>
        <el-card style="margin-bottom: 10px">
          <el-col :span="8">
            <el-form-item label="账号" prop="userName">
              <el-input
                placeholder="请输入"
                v-model="formModel.userName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="角色" prop="roleIds">
              <el-select
                v-model="formModel.roleIds"
                multiple
                style="width: 100%"
              >
                <el-option
                  v-for="item in roleList"
                  :value="item.roleId"
                  :label="item.roleName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账号状态">
              <el-switch
                v-model="formModel.status"
                active-value="0"
                inactive-value="1"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-card>
        <el-card style="margin-bottom: 10px">
          <el-form-item label="权限设置">
            <!-- <el-radio-group v-model="formModel.authSet">
              <el-radio label="1">权限设置</el-radio>
              <el-radio label="2">数据权限</el-radio>
            </el-radio-group> -->
            <div style="display: flex; width: 100%">
              <template>
                <el-form-item label="系统权限">
                  <el-tree
                    class="tree-border"
                    :data="menuOptions"
                    show-checkbox
                    ref="menu"
                    node-key="id"
                    empty-text="加载中，请稍候"
                    :props="defaultProps"
                  ></el-tree>
                </el-form-item>
              </template>
              <template>
                <el-form-item label="数据权限范围">
                  <el-select
                    v-model="formModel.sysRole.dataScope"
                    @change="dataScopeSelectChange"
                  >
                    <el-option
                      v-for="item in dataScopeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  label="数据权限"
                  v-show="formModel.sysRole.dataScope == 2"
                >
                  <el-checkbox
                    v-model="deptExpand"
                    @change="handleCheckedTreeExpand($event, 'dept')"
                    >展开/折叠</el-checkbox
                  >
                  <el-checkbox
                    v-model="deptNodeAll"
                    @change="handleCheckedTreeNodeAll($event, 'dept')"
                    >全选/全不选</el-checkbox
                  >
                  <el-checkbox
                    v-model="formModel.sysRole.deptCheckStrictly"
                    @change="handleCheckedTreeConnect($event, 'dept')"
                    >父子联动</el-checkbox
                  >
                  <el-tree
                    class="tree-border"
                    :data="deptOptions"
                    show-checkbox
                    default-expand-all
                    ref="dept"
                    node-key="id"
                    empty-text="加载中，请稍候"
                    :props="defaultProps"
                  ></el-tree>
                </el-form-item>
              </template>
            </div>
          </el-form-item>
        </el-card>
      </template>
      <template v-if="formModel.userType === 2">
        <el-card style="margin-bottom: 10px">
          <el-form-item label="姓名" required>
            {{ originName }}
            <el-button type="text" @click.native="handleSelectName"
              >请选择</el-button
            >
          </el-form-item>
        </el-card>
        <el-card style="margin-bottom: 10px">
          <el-col :span="8">
            <el-form-item label="账号" prop="userName">
              <el-input
                placeholder="请输入"
                v-model="formModel.userName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账号状态" prop="status">
              <el-switch
                v-model="formModel.status"
                active-value="0"
                inactive-value="1"
              ></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账号有效期" prop="expireTime">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="formModel.expireTime"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-card>
      </template>
      <template v-if="formModel.userType === 3">
        <el-card style="margin-bottom: 10px">
          <el-form-item label="姓名" required>
            {{ originName }}
            <el-button type="text" @click.native="handleSelectName"
              >请选择</el-button
            >
          </el-form-item>
        </el-card>
        <el-card style="margin-bottom: 20px">
          <el-col :span="12">
            <el-form-item label="账号">
              <el-input
                placeholder="请输入"
                v-model="formModel.userName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账号状态">
              <el-switch
                v-model="formModel.status"
                active-value="0"
                inactive-value="1"
              ></el-switch>
            </el-form-item>
          </el-col>
          <el-col v-if="userId && formModel.userType === 3">
            <el-form-item label="子账号">
              <el-card shadow="never">
                <el-table :data="subAccountList" bordered>
                  <el-table-column
                    label="用户ID"
                    align="center"
                    prop="userId"
                  />
                  <el-table-column
                    label="用户账号"
                    align="center"
                    prop="userName"
                  />
                  <el-table-column
                    label="用户昵称"
                    align="center"
                    prop="nickName"
                  />
                  <el-table-column
                    label="手机号码"
                    align="center"
                    prop="phonenumber"
                  />
                  <el-table-column
                    label="账号状态"
                    align="center"
                    prop="status"
                  >
                    <template slot-scope="scope">
                      <el-switch
                        v-model="scope.row.status"
                        active-value="0"
                        inactive-value="1"
                      ></el-switch>
                    </template>
                  </el-table-column>
                </el-table>
                <pagination
                  v-show="total > 0"
                  :total="total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getSubList"
                />
              </el-card>
            </el-form-item>
          </el-col>
        </el-card>
      </template>
      <template v-if="formModel.userType === 4 || formModel.userType === 5">
        <el-card style="margin-bottom: 10px">
          <el-form-item label="姓名" required>
            {{ originName }}
            <el-button type="text" @click.native="handleSelectName"
              >请选择</el-button
            >
          </el-form-item>
        </el-card>
        <el-card style="margin-bottom: 10px">
          <el-col :span="12">
            <el-form-item label="账号">
              <el-input
                placeholder="请输入"
                v-model="formModel.userName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="123">
            <el-form-item label="账号状态">
              <el-switch
                v-model="formModel.status"
                active-value="0"
                inactive-value="1"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-card>
      </template>
      <el-card>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            :row="4"
            v-model="formModel.remark"
            style="width: 600px"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-card>
    </el-form>

    <SelectNameDialog
      :dialogVisible="dialogVisible"
      :userType="formModel.userType"
      :userInfoId="formModel.userInfoId"
      @onClose="dialogVisible = false"
      @onSubmit="handleOnSubmit"
    ></SelectNameDialog>

    <!-- 供应商子账号弹窗 -->
    <el-dialog
      :title="subAccountTitle"
      :visible.sync="subAccountVisible"
      :before-close="handleSubClose"
    >
      <el-form :model="subFormModel" label-width="100px">
        <el-form-item label="姓名">
          <el-input placeholder="请输入" v-model="subFormModel.name"></el-input>
        </el-form-item>
        <el-form-item label="账号">
          <el-input
            placeholder="请输入"
            v-model="subFormModel.userName"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            placeholder="请输入"
            v-model="subFormModel.phone"
          ></el-input>
        </el-form-item>
        <el-form-item label="账号状态">
          <el-switch
            v-model="subFormModel.status"
            active-value="0"
            inactive-value="1"
          ></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="subAccountVisible = false">取 消</el-button>
        <el-button type="primary" @click="subAccountVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { userTypeList } from "@/configEnum";
import SelectNameDialog from "@/components/SelectDialog/SelectNameDialog";
import {
  treeselect as menuTreeselect,
  roleMenuTreeselect,
} from "@/api/system/menu";
import {
  listRole,
  deptTreeSelect,
  getRole,
  dataScope,
  changeRoleStatus,
} from "@/api/system/role";
import { listDept, listDeptChildren } from "@/api/system/dept";
import { addUser, getUser, updateUser, listUser } from "@/api/system/user";
import { validatePhoneNumber } from "@/utils";
import { validateCard } from "@/utils/validator";
export default {
  components: {
    SelectNameDialog,
  },
  data() {
    return {
      originName: "",
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 数据范围选项
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限",
        },
        {
          value: "2",
          label: "自定数据权限",
        },
        {
          value: "3",
          label: "本部门数据权限",
        },
        {
          value: "4",
          label: "本部门及以下数据权限",
        },
        {
          value: "5",
          label: "仅本人数据权限",
        },
      ],
      deptOptions: [],
      // 菜单列表
      menuOptions: [],
      rules: {
        nickName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "change",
          },
        ],
        orgId: [
          {
            required: true,
            message: "请选择机构",
            trigger: "change",
          },
        ],
        deptId: [
          {
            required: true,
            message: "请选择部门",
            trigger: "change",
          },
        ],
        phonenumber: validatePhoneNumber(),
        userName: [
          {
            required: true,
            message: "请输入账号",
            trigger: "change",
          },
        ],
        expireTime: [
          {
            required: true,
            message: "请选择账号有效期",
            trigger: "change",
          },
        ],
        roleIds: [
          {
            required: true,
            message: "请选择角色",
            trigger: "change",
          },
        ],
        idNumber: validateCard(),
      },
      subAccountTitle: "新增子账号",
      subFormModel: {
        name: undefined,
        userName: undefined,
        phone: undefined,
        status: true,
      },
      subAccountVisible: false,
      subAccountList: [],
      userTypeList,
      formModel: {
        expireTime: undefined,
        userInfoId: undefined,
        userType: 1,
        nickName: undefined,
        phonenumber: undefined,
        idNumber: undefined,
        userName: undefined,
        postName: undefined,
        address: undefined,
        birthday: undefined,
        status: "0",
        orgId: "", // 机构
        deptId: "", // 部门
        accountDate: undefined,
        remark: undefined,
        sex: "1",
        roleIds: [],
        sysRole: {
          remark: null,
          roleId: undefined,
          roleName: undefined,
          roleType: undefined,
          roleKey: undefined,
          roleSort: undefined,
          dataScope: "5",
          status: undefined,
          delFlag: undefined,
          flag: undefined,
          menuIds: [],
          deptIds: [],
          permissions: [],
          admin: undefined,
          menuCheckStrictly: true,
          deptCheckStrictly: true,
        },
      },
      sysRole: {
        remark: null,
        roleId: undefined,
        roleName: undefined,
        roleType: undefined,
        roleKey: undefined,
        roleSort: undefined,
        dataScope: 1,
        status: undefined,
        delFlag: undefined,
        flag: undefined,
        menuIds: [],
        deptIds: [],
        permissions: [],
        admin: undefined,
        menuCheckStrictly: true,
        deptCheckStrictly: true,
      },
      dialogVisible: false,
      roleList: [], // 角色列表
      orgList: [], // 机构列表
      deptList: [], // 部门列表
      deptExpand: true,
      deptNodeAll: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        subjectId: null,
      },
    };
  },
  watch: {
    userType(n, o) {},
  },
  methods: {
    handleCardChange(val) {
      this.originName = "";
    },
    // 选择姓名弹框确认
    handleOnSubmit(userInfoId, name) {
      console.log(name);
      this.originName = name;
      this.formModel = { ...this.formModel, userInfoId };
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.handleValidateSuccess();
        } else {
          return false;
        }
      });
    },
    handleValidateSuccess() {
      //用户
      if (this.formModel.userType === 1) {
        this.formModel.sysRole.menuIds = this.getMenuAllCheckedKeys();
        this.formModel.sysRole.deptIds = this.getDeptAllCheckedKeys();
        // this.formModel.sysRole = this.sysRole;
      }
      console.log(this.formModel);

      if (!this.userId) {
        addUser({
          ...this.formModel,
        }).then((res) => {
          console.log(res);
          this.handleOkToLink();
        });
      } else {
        updateUser({
          ...this.formModel,
        }).then((res) => {
          console.log(res);
          this.handleOkToLink();
        });
      }
    },
    handleOkToLink() {
      this.$modal.msgSuccess("操作成功");
      // this.getUserInfo(this.userId);
      // this.$closeSelectedTag(this.$route)
      this.$router.push({
        path: "/system/user",
      });
    },
    handleOrg() {
      // 获取部门列表
      listDeptChildren({
        orgId: this.formModel.orgId,
      }).then((res) => {
        console.log(res);
        this.deptList = res.data;
      });
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data;
      });
    },
    /** 根据角色ID查询部门树结构 */
    getDeptTree(roleId) {
      return deptTreeSelect(roleId).then((response) => {
        this.deptOptions = response.depts;
        return response;
      });
    },
    handleBack() {
      this.$router.push({
        path: "/system/user",
      });
    },
    removeSubAccount(row) {
      this.$confirm("确定要删除此账号吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    updateSubAccount(row) {
      this.subAccountVisible = true;
      this.subAccountTitle = "修改子账号";
      this.subFormModel = {
        ...this.subFormModel,
        ...row,
      };
    },
    addSubAccount() {
      this.subAccountVisible = true;
    },
    handleSubClose() {},
    handleSelectName() {
      this.dialogVisible = true;
    },
    getRoleList() {
      /** 查询角色列表 */
      this.loading = true;
      listRole({
        pageNum: 1,
        pageSize: 10000,
      }).then((response) => {
        this.roleList = response.rows;
      });
    },
    /** 查询机构列表 */
    getOrgList() {
      listDept({
        orgType: 1,
      }).then((response) => {
        this.orgList = this.handleTree(response.data, "orgId");
        console.log(this.orgList);
      });
    },
    getUserInfo(userId) {
      if (userId) {
        getUser(userId).then((response) => {
          console.log("11123", response);
          this.originName = response.data.nickName;
          this.formModel = {
            ...this.formModel,
            ...response.data,
            ...response.sysUserInfo,
          };
          if (response.sysUserInfo.sysRole === null) {
            this.formModel.sysRole = this.sysRole;
          }
          this.handleOrg();
          if (this.formModel.sysRole?.roleId) {
            const roleMenu = this.getRoleMenuTreeselect(
              this.formModel.sysRole.roleId
            );
            getRole(this.formModel.sysRole.roleId).then((response) => {
              this.form = response.data;
              this.open = true;
              this.$nextTick(() => {
                roleMenu.then((res) => {
                  let checkedKeys = res.checkedKeys;
                  checkedKeys.forEach((v) => {
                    this.$nextTick(() => {
                      this.$refs.menu.setChecked(v, true, false);
                    });
                  });
                });
              });
            });
            this.handleDataScope(this.formModel.sysRole.roleId);
          }
          if (this.formModel.userType === 3) {
            this.getSubList();
          }
        });
      }
    },
    getSubList() {
      listUser({
        ...this.queryParams,
        subjectId: Number(this.$route.query.id),
      }).then((response) => {
        this.subAccountList = response.rows;
        this.total = response.total;
      });
    },
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then((response) => {
        this.menuOptions = response.menus;
        return response;
      });
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if (value !== "2") {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if (value !== "2") {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == "menu") {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == "dept") {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == "menu") {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
      } else if (type == "dept") {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == "menu") {
        this.form.menuCheckStrictly = value ? true : false;
      } else if (type == "dept") {
        this.form.deptCheckStrictly = value ? true : false;
      }
    },
    /** 分配数据权限操作 */
    handleDataScope(roleId) {
      const deptTreeSelect = this.getDeptTree(roleId);
      getRole(roleId).then((response) => {
        this.$nextTick(() => {
          deptTreeSelect.then((res) => {
            this.$refs.dept.setCheckedKeys(res.checkedKeys);
          });
        });
      });
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
  },
  created() {
    this.getDeptTree(1);
    this.getMenuTreeselect();
    // 获取机构列表
    this.getOrgList();
    // 获取角色列表
    this.getRoleList();
    this.userId = this.$route.query.id;
    if (this.userId) {
      this.getUserInfo(this.userId);
    }
  },
  computed: {
    pickerOptions() {
      return {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      };
    },
    title() {
      return !this.$route?.query?.id ? "新增用户" : "修改用户";
    },
  },
};
</script>

<style lang="scss" scoped>
.tree-border {
  width: 200px;
}
</style>
